package com.pm.common.utils;

import com.pm.common.core.domain.entity.ProjectTempleteDefine;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.stream.Collectors;

public class ProjectUtils {

    /**
     * 节点数据树形化
     * @param list
     * @return
     */
    public static List<ProjectTempleteDefine> buildProjectTempleteDefineTree(List<ProjectTempleteDefine> list) {

        List<ProjectTempleteDefine> returnList = new ArrayList<>();
        List<Long> tempList = list.stream().map(ProjectTempleteDefine::getId).collect(Collectors.toList());
        for (Iterator<ProjectTempleteDefine> iterator = list.iterator(); iterator.hasNext();)
        {
            ProjectTempleteDefine projectTempleteDefine = (ProjectTempleteDefine) iterator.next();
            // 如果是顶级节点, 遍历该父节点的所有子节点
            if (!tempList.contains(projectTempleteDefine.getParentId()))
            {
                recursionFn(list, projectTempleteDefine);
                returnList.add(projectTempleteDefine);
            }
        }
        if (returnList.isEmpty())
        {
            returnList = list;
        }
        return returnList;
    }


    private static void recursionFn(List<ProjectTempleteDefine> list, ProjectTempleteDefine projectTempleteDefine) {
        // 得到子节点列表
        List<ProjectTempleteDefine> childList = getChildList(list, projectTempleteDefine);
        projectTempleteDefine.setChildren(childList);
        for (ProjectTempleteDefine tChild : childList)
        {
            if (hasChild(list, tChild))
            {
                recursionFn(list, tChild);
            }
        }
    }

    private static boolean hasChild(List<ProjectTempleteDefine> list, ProjectTempleteDefine tChild) {
        return getChildList(list, tChild).size() > 0;
    }

    private static List<ProjectTempleteDefine> getChildList(List<ProjectTempleteDefine> list, ProjectTempleteDefine projectTempleteDefine) {

        List<ProjectTempleteDefine> tlist = new ArrayList<>();
        Iterator<ProjectTempleteDefine> it = list.iterator();
        while (it.hasNext())
        {
            ProjectTempleteDefine n = (ProjectTempleteDefine) it.next();
            if (n.getParentId().intValue() == projectTempleteDefine.getId().intValue())
            {
                tlist.add(n);
            }
        }
        return tlist;
    }
}
